package org.advanced.transaction;

import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * @author John.zhang
 * @version Id: Transaction, v 1.0 2020/12/22 17:57 ZhiYong Exp $
 * redis事务(不具备原子性，redis只会识别错误的语法来进行回滚事务)
 * <p>
 * 命令
 * multi -> decrby key value ->incrby key2 value2 ->exec  /取消事务：multi -> set key value discard/监视watch unwatch
 * set key value -> watch key ->multi->incrby key value (如果有其他地方改变了value，这时候结果会执行失败) exec
 */
public class Transaction {

    final static String key = "trxKey";

    public static void main(String[] args) {
        new Thread() {
            @Override
            public void run() {
                Jedis jedis = new Jedis("10.181.144.255", 6379);
                String watch = jedis.watch(key);
                System.out.println("method1线程[" + Thread.currentThread().getName() + "]watch结果：" + watch);
                redis.clients.jedis.Transaction multi = jedis.multi();
                multi.set(key, "2673-thread1");
                // 让Thread2先执行完
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                List<Object> exec = multi.exec();
                System.out.println("method1执行结果：" + exec);
                jedis.unwatch();
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                Jedis jedis = new Jedis("127.0.0.1", 6379);
                String watch = jedis.watch(key);
                System.out.println("method2线程[" + Thread.currentThread().getName() + "]watch结果：" + watch);
                redis.clients.jedis.Transaction multi = jedis.multi();
                multi.set(key, "2673-thread2");
                List<Object> exec = multi.exec();
                System.out.println("method2执行结果：" + exec);
            }
        }.start();

    }
}
